import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:convert';

import 'package:flutterapp2/model/base_response.dart';

class NetworkPlugin {
  static const MethodChannel _channel = const MethodChannel('network_plugin');

  /// 发送GET请求
  /// [path] : 请求的path，不是url
  /// [params] : 请求参数
  /// 返回 json 字符串
  static Future<String> rawGet(String path, Map params) async {
    return await _channel
        .invokeMethod('rawGet', {'path': path, 'params': params});
  }

  /// 发送GET请求
  /// [path] : 请求的path，不是url
  /// [params] : 请求参数
  /// 返回 Response
  static Future<BaseResponse> get(String path, Map params) async {
    String responseString = await rawGet(path, params);
    BaseResponse response = _extractResponse(responseString);
    return response;
  }

  /// 发送POST请求
  /// [path] : 请求的path，不是url
  /// [params] : 请求参数
  /// 返回 json 字符串
  static Future<String> rawPost(String path, Map params) async {
    return await _channel
        .invokeMethod('rawPost', {'path': path, 'params': params});
  }

  /// 发送POST请求
  /// [path] : 请求的path，不是url
  /// [params] : 请求参数
  /// 返回 Response
  static Future<BaseResponse> post(String path, Map params) async {
    String responseString = await rawPost(path, params);
    BaseResponse response = _extractResponse(responseString);
    return response;
  }

  static BaseResponse _extractResponse(String responseString) {
    try {
      return BaseResponse.fromJson(json.decode(responseString));
    } catch (e, s) {
      print(s);
      return null;
    }
  }
}
